package com.data.modules.log.common;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Component;

import javax.annotation.Nonnull;
import java.util.function.Supplier;

/**
 * @author z
 * ApplicationContext对象的获取
 */
@Component
public class ApplicationContextHolder implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    private static BeanDefinitionRegistry beanDefinitionRegistry;

    @Override
    public void setApplicationContext(@Nonnull ApplicationContext applicationContext) throws BeansException {
        ApplicationContextHolder.applicationContext = applicationContext;
        ConfigurableApplicationContext configurableApplicationContext = (ConfigurableApplicationContext) applicationContext;
        ConfigurableListableBeanFactory beanFactory = configurableApplicationContext.getBeanFactory();
        beanDefinitionRegistry = (BeanDefinitionRegistry) beanFactory;
    }

    /**
     * 全局的applicationContext对象
     * @return applicationContext
     */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    @SuppressWarnings("unchecked")
    public static <T> T getBean(String beanName) {
        return (T) applicationContext.getBean(beanName);
    }

    public static <T> T getBean(Class<T> clazz) {
        return applicationContext.getBean(clazz);
    }

    public static <T> void registryBean(Class<T> clazz, Supplier<T> supplier) {
        BeanDefinitionBuilder definition = BeanDefinitionBuilder.genericBeanDefinition(clazz, supplier);
        beanDefinitionRegistry.registerBeanDefinition(StrUtil.toCamelCase(clazz.getSimpleName()), definition.getBeanDefinition());
        T bean = applicationContext.getBean(clazz);
        System.out.println("bean = " + JSONObject.toJSONString(bean));
    }

    public static <T> void removeBean(Class<T> clazz) {
        beanDefinitionRegistry.removeBeanDefinition(StrUtil.toCamelCase(clazz.getSimpleName()));
        boolean b = applicationContext.containsBean(StrUtil.toCamelCase(clazz.getSimpleName()));
        System.out.println("bean remove = " + !b);
    }

}
